import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class MyHttpClient {
    private Socket socket;
    private String ip;
    private int port;

    public MyHttpClient(String ip,int port) throws IOException {
        this.ip = ip;
        this.port = port;
        socket = new Socket(ip,port);
    }

    public String GET(String url) throws IOException {
        // 构造字符串
        StringBuilder request = new StringBuilder();
        // 构造首行
        request.append("GET " + url + "HTTP/1.1\n");
        // 构造header
        request.append("Host: " + ip + ":" + port + "\n");
        // 构造空行
        request.append("\n");
        // 发送数据
        OutputStream stream = socket.getOutputStream();
        stream.write(request.toString().getBytes());
        // 读取 request 响应
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024 * 1024];
        int n = inputStream.read(bytes);
        return new String(bytes,0,n,"UTF-8");
    }

    public String POST(String url,String body) throws IOException {
        StringBuilder request = new StringBuilder();
        // 构造首行
        request.append("POST " + url + "HTTP/1.1\n");
        // 构造 header
        request.append("Host: " + ip + ":" + port + "\n");
        request.append("Content-Length: " + body.getBytes().length + "\n");
        request.append("Content-Type: text/plain\n");
        // 构造空行
        request.append("\n");
        // 构造 body
        request.append(body);
        // 发送数据
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(request.toString().getBytes());
        // 接收数据
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024 * 1024];
        int n = inputStream.read(bytes);
        return new String(bytes,0,n,"utf-8");
    }
}
